package org.zjx.swing.view;

import javax.swing.*;
import java.awt.*;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import java.io.File;
import java.awt.image.BufferedImage;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableCellRenderer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import lombok.SneakyThrows;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.zjx.entity.Coordinate;
import org.zjx.util.HwndUtil;
import org.zjx.util.ImageUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class PropView extends JFrame {
    private JTextField[] textFields = new JTextField[5];
    private Robot robot;
    private BufferedImage screen;
    private JTable table = new JTable(4, 5);
    private JTextArea textAreaDescription;
    private JLabel thumbnailLabel;
    private JButton captureConfirmButton;
    private JLabel rightNumberLabel; // 3 展示区域的标签
    private JLabel leftNumberLabel; // 2 展示区域的标签，用于显示左边图片
    private int currentIndex = 0;
    private BufferedImage lin;
    private List<BufferedImage> count;
    private List<BufferedImage> images;
    private List<BufferedImage> count2;
    private List<BufferedImage> images2;
    private BufferedImage image;
    private String type;
    private JTextArea xmlFilesTextArea = new JTextArea(5, 20);
    private File lastSelectedFile;
    private CustomTableCellRenderer tableCellRenderer;
    private JTextField[] rangeTextFields = new JTextField[4];
    private JComponent textComponent;

    public PropView() {
        setTitle("道具信息工具");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 创建左右面板
        JPanel leftPanel = createLeftPanel();
        // 修改左面板首选宽度为窗口宽度的 60%
        leftPanel.setPreferredSize(new Dimension(450, 600));

        JPanel rightPanel = new JPanel(new BorderLayout()); // 修改布局为 BorderLayout
        // 相应调整右面板首选宽度为窗口宽度的 40%
        rightPanel.setPreferredSize(new Dimension(320, 600));
        rightPanel.setMinimumSize(new Dimension(300, 600)); // 增大最小宽度

        // 第一个区域，占 10%
        JPanel newTopPanel = new JPanel();
        GridBagConstraints gbcTop = new GridBagConstraints();
        gbcTop.insets = new Insets(5, 5, 5, 5);
        gbcTop.fill = GridBagConstraints.HORIZONTAL;

        // 添加标签
        JLabel newLabel = new JLabel("手动截图：");
        gbcTop.gridx = 0;
        gbcTop.gridy = 0;
        gbcTop.gridwidth = 1;
        newTopPanel.add(newLabel, gbcTop);

        // 定义 4 个输入框
        JTextField[] newTextFields = new JTextField[4];
        // 估算能容纳 3 个数字的宽度，这里可以根据字体大小调整
        int preferredWidth = 30;
        int preferredHeight = 25;
        Dimension preferredSize = new Dimension(preferredWidth, preferredHeight);
        for (int i = 0; i < 4; i++) {
            newTextFields[i] = new JTextField(3); // 设置列数为 3
            newTextFields[i].setPreferredSize(preferredSize);
            newTextFields[i].setMinimumSize(preferredSize);
            newTextFields[i].setMaximumSize(preferredSize);
            gbcTop.gridx = i + 1;
            gbcTop.gridy = 0;
            gbcTop.gridwidth = 1;
            newTopPanel.add(newTextFields[i], gbcTop);
        }

        // 新增确认按钮
        JButton newConfirmButton = new JButton("确认");
        // 可根据需求添加按钮点击事件监听
        newConfirmButton.addActionListener(e -> {
            JTextField textField0 = newTextFields[0];
            JTextField textField1 = newTextFields[1];
            JTextField textField2 = newTextFields[2];
            JTextField textField3 = newTextFields[3];
            String[] number = new String[4];
            number[0] = textField0.getText();
            number[1] = textField1.getText();
            number[2] = textField2.getText();
            number[3] = textField3.getText();
            int[] a = new int[4];
            a[0] = Integer.parseInt(number[0]);
            a[1] = Integer.parseInt(number[1]);
            a[2] = Integer.parseInt(number[2]);
            a[3] = Integer.parseInt(number[3]);
            lin =ImageUtil.subImage(getGameScreen(),ImageUtil.getRect(a[0], a[1], a[2], a[3])) ;
            if (lin != null) {
                ImageIcon icon = new ImageIcon(lin);
                // 使用已有的 showImageInLabel 方法将图片显示在左分割面板的 JLabel 中
                showImageInLabel(icon, leftNumberLabel);
            } else {
                System.err.println("未能获取到有效的子图片");
                leftNumberLabel.setText("未能获取到有效的子图片");
            }
        });
        // 设置确认按钮的布局
        gbcTop.gridx = 5;
        gbcTop.gridy = 0;
        gbcTop.gridwidth = 1;
        newTopPanel.add(newConfirmButton, gbcTop);


        // 第二个区域，占 30%
        JPanel buttonPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.weighty = 0.30;
        gbc.fill = GridBagConstraints.NONE;

        // 统一字体设置（放大2pt）
        Font labelFont = UIManager.getFont("Label.font");
        if (labelFont != null) {
            labelFont = labelFont.deriveFont(labelFont.getSize() + 2f);
        } else {
            labelFont = new Font("微软雅黑", Font.PLAIN, 14);
        }
        UIManager.put("Label.font", labelFont);

        // 确认截取按钮
        final Logger LOGGER = Logger.getLogger(PropView.class.getName());
        this.captureConfirmButton = new JButton("确认截取");
        this.captureConfirmButton.addActionListener(e -> {
            try {
                performCaptureConfirmation(LOGGER);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 4; // 跨 4 列，占满宽度
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.NORTH;
        buttonPanel.add(captureConfirmButton, gbc);

        // 新增切换道具栏按钮
        JButton switchInventoryButton = new JButton("切换道具栏截取");
        // 可根据需求添加按钮点击事件监听
        switchInventoryButton.addActionListener(e -> {
            inventory2();
            for (int i = 0; i < 20; i++) {
                deDifferent(images.get(i),images2.get(i));
            }
            updateImageLabels();
// 新增逻辑：比较 images 和 XML 文件中的 ImageString
            if (lastSelectedFile != null) {
                try {
                    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                    Document doc = docBuilder.parse(lastSelectedFile);

                    NodeList matrixNodes = doc.getElementsByTagName("Matrix");
                    for (int i = 0; i < images.size(); i++) {
                        String imageString = ImageUtil.bufferedImageToString(images.get(i));
                        for (int j = 0; j < matrixNodes.getLength(); j++) {
                            Element matrixElement = (Element) matrixNodes.item(j);
                            Element imageStringElement = (Element) matrixElement.getElementsByTagName("ImageString").item(0);
                            if (imageStringElement != null && imageString.equals(imageStringElement.getTextContent())) {
                                int columns = 5;
                                int row = i / columns;
                                int col = i % columns;
                                if (row >= 0 && row < 4 && col >= 0 && col < 5) {
                                    table.setValueAt("✔", row, col);
                                }
                                break;
                            }
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(PropView.this, "比较图片和 XML 文件时出错。");
                }
            }
        });

        // 设置切换道具栏按钮的布局
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 4;
        gbc.insets = new Insets(0, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.NORTH;
        buttonPanel.add(switchInventoryButton, gbc);

        // 新增两个按钮
        JButton newButton1 = new JButton("上一个");
        JButton newButton2 = new JButton("下一个");

        // 设置按钮的最小、首选和最大尺寸，确保长度一致
        Dimension buttonSize = new Dimension(140, 25); // 可根据实际情况调整尺寸
        newButton1.setPreferredSize(buttonSize);
        newButton1.setMinimumSize(buttonSize);
        newButton1.setMaximumSize(buttonSize);
        newButton2.setPreferredSize(buttonSize);
        newButton2.setMinimumSize(buttonSize);
        newButton2.setMaximumSize(buttonSize);

        // 为“上一个”按钮添加事件监听
        newButton1.addActionListener(e -> handlePreviousButtonClick());
        // 为“下一个”按钮添加事件监听
        newButton2.addActionListener(e -> handleNextButtonClick());

        // 设置新按钮的布局
        gbc.gridy = 2;
        gbc.gridwidth = 2; // 每个按钮跨 2 列
        // 统一按钮的 insets，确保两个按钮有相同的外边距
        gbc.insets = new Insets(0, 5, 10, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.NORTH; // 设置组件靠上对齐
        buttonPanel.add(newButton1, gbc);

        gbc.gridx = 2;
        buttonPanel.add(newButton2, gbc);

        table.setDefaultRenderer(Object.class, new CustomTableCellRenderer());

        // 文件夹选择按钮
        JButton folderSelectButton = new JButton("选择 XML 文件");
        // 固定按钮大小
        Dimension buttonSize2 = new Dimension(120, 25);
        folderSelectButton.setPreferredSize(buttonSize2);
        folderSelectButton.setMinimumSize(buttonSize2);
        folderSelectButton.setMaximumSize(buttonSize2);

        xmlFilesTextArea.setEditable(false);
        xmlFilesTextArea.setLineWrap(true);
        xmlFilesTextArea.setWrapStyleWord(true);
        // 将字体放大一倍
        Font originalFont = xmlFilesTextArea.getFont();
        xmlFilesTextArea.setFont(originalFont.deriveFont(originalFont.getSize()));
        // 固定文本区域大小
        Dimension textAreaSize = new Dimension(200, 20);
        xmlFilesTextArea.setPreferredSize(textAreaSize);
        xmlFilesTextArea.setMinimumSize(textAreaSize);
        xmlFilesTextArea.setMaximumSize(textAreaSize);
        xmlFilesTextArea.setVisible(false);


        folderSelectButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
                }

                @Override
                public String getDescription() {
                    return "XML Files (*.xml)";
                }
            });
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int result = fileChooser.showOpenDialog(PropView.this);
            if (result == JFileChooser.APPROVE_OPTION) {
                lastSelectedFile = fileChooser.getSelectedFile(); // 保存选择的文件
                xmlFilesTextArea.setText(lastSelectedFile.getName());

                // 隐藏按钮，显示展示框
                folderSelectButton.setVisible(false);
                xmlFilesTextArea.setVisible(true);
            }
            scanXmlFiles(lastSelectedFile);
        });
        // 添加文件夹选择按钮到第二区域最下面
        gbc.gridy = 3;
        gbc.gridx = 0;
        gbc.gridwidth = 4; // 设置为 4，使其跨 4 列占满宽度
        gbc.insets = new Insets(0, 10, 0, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL; // 水平填充
        gbc.anchor = GridBagConstraints.NORTH; // 组件靠上对齐
        buttonPanel.add(folderSelectButton, gbc);

        // 添加展示框到第二区域最下面
        gbc.gridx = 0;
        gbc.gridwidth = 4;
        gbc.insets = new Insets(0, 10, 0, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        buttonPanel.add(xmlFilesTextArea, gbc);

        JPanel inputPanel = new JPanel(new GridBagLayout());
        gbc.weighty = 0.45;
        String[] labels = {"名字", "位置","类型", "备注"};
        JComponent[] textComponents = new JComponent[5];
        int baseGridY = 2;

        for (int i = 0; i < labels.length; i++) {
            JLabel label = new JLabel(labels[i] + "：");
            if (i == 3) {
                textAreaDescription = new JTextArea(3, 20);
                textAreaDescription.setLineWrap(true);
                textAreaDescription.setWrapStyleWord(true);
                textComponent = new JScrollPane(textAreaDescription);
                ((JScrollPane) textComponent).setBorder(BorderFactory.createEtchedBorder());
            } else if (i == 2) {
                String[] options = {"烹饪", "三药", "普通", "任务", "传送","回血","回蓝","复活","装备"};
                JComboBox<String> comboBox = new JComboBox<>(options);
                textComponent = comboBox;
                // 由于是 JComboBox，无需赋值给 textFields[2]
            } else {
                JTextField textField = new JTextField();
                textField.setPreferredSize(new Dimension(200, 25));
                textField.setMaximumSize(new Dimension(200, 25));
                textComponent = textField;
                if (i < 2) { // 仅将前两个 JTextField 赋值给 textFields
                    textFields[i] = textField;
                }
            }

            gbc.insets = new Insets(0, 10, 0, 5);
            gbc.gridx = 0;
            gbc.gridy = baseGridY + i;
            gbc.gridwidth = 1;
            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            inputPanel.add(label, gbc);

            gbc.insets = new Insets(0, 5, 0, 10);
            gbc.gridx = 1;
            gbc.gridwidth = 3;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            inputPanel.add(textComponent, gbc);

            textComponents[i] = textComponent;
        }

        // 创建 5*4 的表格
        table.setDefaultEditor(Object.class, null);
        table.setTableHeader(null); // 隐藏表头

        int number = 1;
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 5; col++) {
                table.setValueAt(number++, row, col);
            }
        }

        // 固定表格单元格大小，使每个格子能展示2个数字
        int cellWidth = 30;
        int cellHeight = 30;
        table.setRowHeight(cellHeight);
        for (int i = 0; i < table.getColumnCount(); i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(cellWidth);
        }

        // 直接添加表格，而不是使用 JScrollPane
        gbc.gridy = baseGridY + labels.length;
        gbc.gridx = 0;
        gbc.gridwidth = 4;
        gbc.insets = new Insets(0, 10, 0, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        inputPanel.add(table, gbc);


        // 第四个区域，占 20%
        JPanel savePanel = new JPanel(new BorderLayout());
        gbc.weighty = 0.15; // 设置权重为 0.15
        // 添加保存按钮（优化布局）

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(e -> {
            String name = textFields[0].getText().trim();
            String position = textFields[1].getText().trim();
            // 移除从 textFields[2] 获取功能值的代码
            String description = textAreaDescription.getText().trim();
            System.out.println(name + " " + position + " " + description);
            String type = null;

            if (textComponents[2] instanceof JComboBox) {
                JComboBox<String> typeComboBox = (JComboBox<String>) textComponents[2];
                type = (String) typeComboBox.getSelectedItem();
            } else if (textComponents[2] instanceof JTextField) {
                JTextField textField = (JTextField) textComponents[2];
                type = textField.getText().trim();
            } else {
                JOptionPane.showMessageDialog(PropView.this, "类型信息无效", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (lastSelectedFile == null) {
                JOptionPane.showMessageDialog(PropView.this, "请先选择一个 XML 文件", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            try {
                String imageString = ImageUtil.bufferedImageToString(image);
                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                Document doc;

                if (lastSelectedFile.exists() && lastSelectedFile.length() > 0) {
                    try {
                        doc = docBuilder.parse(lastSelectedFile);
                    } catch (Exception parseEx) {
                        doc = docBuilder.newDocument();
                        Element rootElement = doc.createElement("PropInfoList");
                        doc.appendChild(rootElement);
                        JOptionPane.showMessageDialog(PropView.this, "所选 XML 文件格式错误，已创建新的 XML 结构", "警告", JOptionPane.WARNING_MESSAGE);
                    }
                } else {
                    doc = docBuilder.newDocument();
                    Element rootElement = doc.createElement("PropInfoList");
                    doc.appendChild(rootElement);
                }

                Element rootElement = doc.getDocumentElement();
                Element propInfoElement = doc.createElement("PropInfo");
                rootElement.appendChild(propInfoElement);
                Element matrixElement = doc.createElement("Matrix");
                propInfoElement.appendChild(matrixElement);
                Element positionElement = doc.createElement("Position");
                positionElement.setTextContent(position);
                matrixElement.appendChild(positionElement);
                Element nameElement = doc.createElement("Name");
                nameElement.setTextContent(name);
                matrixElement.appendChild(nameElement);
                Element descriptionElement = doc.createElement("Description");
                descriptionElement.setTextContent(description);
                matrixElement.appendChild(descriptionElement);
                Element typeElement = doc.createElement("Type");
                typeElement.setTextContent(type);
                matrixElement.appendChild(typeElement);
                Element imageStringElement = doc.createElement("ImageString");
                imageStringElement.setTextContent(imageString);
                matrixElement.appendChild(imageStringElement);

                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StreamResult result = new StreamResult(lastSelectedFile);
                transformer.transform(source, result);

                JOptionPane.showMessageDialog(PropView.this, "保存成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(PropView.this, "保存失败，请检查权限或目录是否可写。", "错误", JOptionPane.ERROR_MESSAGE);
            }
            scanXmlFiles(lastSelectedFile);
        });
        savePanel.add(saveButton, BorderLayout.EAST);

        // 创建一个新的面板，用于包含 newTopPanel 和 buttonPanel
        JPanel northPanel = new JPanel(new BorderLayout());
        northPanel.add(newTopPanel, BorderLayout.NORTH);
        northPanel.add(buttonPanel, BorderLayout.CENTER);

        // 将四个区域添加到右面板
        rightPanel.add(northPanel, BorderLayout.NORTH);
        rightPanel.add(inputPanel, BorderLayout.CENTER);
        rightPanel.add(savePanel, BorderLayout.SOUTH);

        // 添加面板到主窗口
        add(leftPanel, BorderLayout.WEST);
        add(rightPanel, BorderLayout.EAST);

        setVisible(true);

        tableCellRenderer = new CustomTableCellRenderer();
        table.setDefaultRenderer(Object.class, tableCellRenderer);
    }

    //去异  
    public static void deDifferent(BufferedImage image,BufferedImage image2) {
        if (image == null || image2 == null) {
            throw new NullPointerException("image or background is null");
        }
        if (image.getWidth() != image2.getWidth() || image.getHeight() != image2.getHeight()) {
            throw new IllegalArgumentException("Image dimensions don't match");
        }
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                if (image.getRGB(x, y) != image2.getRGB(x, y)) {
                    image.setRGB(x, y, 0x00FFFFFF);
                }
            }
        }
    }

    @SneakyThrows
    public void inventory() {
        count = new ArrayList<>(20);
        images = new ArrayList<>(20);
        BufferedImage screen = getGameScreen();
        for (int i = 0; i < 20; i++) {
            BufferedImage[] image = dispose(screen,i);
            count.add(image[0]);
            images.add(image[1]);
        }
    }

    @SneakyThrows
    public void inventory2() {
        count2 = new ArrayList<>(20);
        images2 = new ArrayList<>(20);
        BufferedImage screen = getGameScreen();
        for (int i = 0; i < 20; i++) {
            BufferedImage[] image = dispose2(screen,i);
            count2.add(image[0]);
            images2.add(image[1]);
        }
    }

    //返回道具图片
    public BufferedImage[] dispose(BufferedImage screen, int index) throws Exception {
        //找到道具栏
        WinDef.RECT inventorRect = getBoundsNow(screen);
        //找到道具
        WinDef.RECT rect = getGoodsPointRect(new Coordinate(inventorRect.left + 251, inventorRect.top + 56), index);
        //找到道具信息
        BufferedImage image = cutImage(screen, rect);
        //找到道具数量
        BufferedImage[] phone = new BufferedImage[2];
        int interval = 8;
        phone[0] = countImage(image);
        phone[1] = image.getSubimage(interval, interval, image.getWidth() - interval * 2, image.getHeight() - interval * 2);
        return phone ;
    }

    public BufferedImage[] dispose2(BufferedImage screen, int index) throws Exception {
        //找到道具栏
        WinDef.RECT inventorRect = getBoundsNow2(screen);
        //找到道具
        WinDef.RECT rect2 = getGoodsPointRect(new Coordinate(inventorRect.left + 26, inventorRect.top + 200), index);
        //找到道具信息
        BufferedImage image2 = cutImage(screen, rect2);
        //找到道具数量
        BufferedImage[] phone = new BufferedImage[2];
        int interval = 8;
        phone[0] = countImage(image2);
        phone[1] = image2.getSubimage(interval, interval, image2.getWidth() - interval * 2, image2.getHeight() - interval * 2);
        return phone ;
    }

    public WinDef.RECT getBoundsNow(BufferedImage screen) {
        try {
            List<Point> points = ImageUtil.matchTemplate(screen, reference());
            if (points.isEmpty()) return null;
            WinDef.RECT rect = new WinDef.RECT();
            rect.left = points.get(0).x - 239;
            rect.top = points.get(0).y - 2;
            rect.right = points.get(0).x + 294;
            rect.bottom = points.get(0).y + 327;
            return rect;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public WinDef.RECT getBoundsNow2(BufferedImage screen) {
        try {
            List<Point> points = ImageUtil.matchTemplate(screen, reference2());
            if (points.isEmpty()) return null;
            WinDef.RECT rect = new WinDef.RECT();
            rect.left = points.get(0).x - 121;
            rect.top = points.get(0).y - 4;
            rect.right = points.get(0).x + 187;
            rect.bottom = points.get(0).y + 444;
            return rect;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public BufferedImage reference() {
        String image = "iVBORw0KGgoAAAANSUhEUgAAADcAAAAOCAIAAAAEzBN0AAAEMElEQVR4Xo1VC0+aVxjmZzUx2dS2SztXi45Zda26rmo1OA0bq1ZTdZMqdQasWwvKxUuROT+LFLWCq7rhvEyKAwRcrU4HaHGxXtqmJlvHnsORjy8fzvTNky/Pec97ec57DkGQkq05IVSx6B10JWWqKa9sslbJbdxdUYmROL+xxSEngDNb3EdiRNFIkaqs3oJdsox5uHUOPSxizjrFo1rFI36kUCWIRCLWn5dp9Ds5HVgOWL3gZy93gmv7HGzFpCx15FhLu9LNNsaSGV0EGZ9Z4cdFDVuSmyN871FWXjckkHxNQlNztPxNjnUxTmg9lacDb+6wVzQM81DZbMVWvpShEr/tmcXyvQI9OduF9oxSAw8n83TseULh/d391zt7BLQd5cDei4OkD9vJLNmpvpvVcaHkXlnNIIBQw31ncdVg/ufM2fxOGpAWVXmMFUZVXpORY9+6O5ksUrE4EftSwgWCH7uD0441gNYBsc8TgJ/K1RGV0Lu1/aqk2gyVnI5xM4/5qUokYNkz4FR02Hlo1U5FoirRtavfoTH+WlH7AB4c7J83//IKUusfcqcX6PF1ekKBjV0KuvVnaJdiwbsx8NCb9km7QNc7g40FTyC7iIjIF3eDZJcaCIp0K2t/La9uJQuVQFruHVoFjXl4E5VCVbITmnWup3ykUvfM6vvmWcBvn/sDRFwzyAy7sXS4Aptb+wBkDY0tWqye9cDzzfAe8NtiEAEub1CA9m5fCKAqE42nUnPvl8ZWK0HbOAv5dxMRjkrbpB/L83lqmsi7X2nDMOVmm9fj34Dnp+ll64QPRG+cQWUQLKln6Wl4am6Fr/KwbgxzzrXEWf6fFUoMCDOPkglFEkpRwC+tN1Gemtmae1XPWBZ8TzZpirTOJK76YXvnFTicIz96EYAwvspEoyohsfomeWryNpvkxgAPqI4tpXocYcb7DgNDbjZRIk8lgDm9eHkA0F6JHGNGGFQ2uX0BgKqEcE7RpscuzDIMgt40+XgzjbiQWPLl95G3U4n7xRQAmk7564O/ozwMNCgs6E5Urq5vbe+8PJPdwmkXt4kpP2JiUFbUMDgiZkbbiD7VbDzbkylGuVLeUiUul9/sKJPW9wmKyvV0MTm1VFHTe13GxPEVI6k2ppxrSv6AoKBM43tCHvucc5Uqxjc1Uz49v0orXJc9oIfhqbwq7Sr+ohPk/RzysvFCaFh5dT9NhHn8QeosvdaN5dLyZjD0nBSJtib/kOaRhSuf6dgHkWgTdr/yro3yermZZhLEZpxx8fbvT59FyNO0YQlZEaLycBcXx6127iI5HpCWpcAUTgubH44d/uDMI06UPSNq6WXIvxe1yrp+QW6hiu168vytS8XtheV6HpCWeantRqMpru8oXBZr0RjkdEbzHe04dys9R4mbkbVYhB/fTkxMTZdDCibF8yOrttGE73/BzvrpR1H1/AAAAABJRU5ErkJggg==";
        try {
            return ImageUtil.stringToBufferedImage(image);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public BufferedImage reference2() {
        String image = "iVBORw0KGgoAAAANSUhEUgAAAD8AAAAQCAIAAAAuxzBrAAAC6UlEQVR4Xo1Wa0/bQBD0B152/Irt2OCEkBQLCqKFFqkqKo1oRaRUlSL6rf/D/1907tZstuvYsBqd7mbn5uZsB+GsH29Xi+tvtxXw+aKsny4IZyfZbJzOj3NmVosrKDEu7yomu7C8O2/0D9fr5e2f1R23fi/Ofy8u7dhgdf8y/vgA8frxBnoEW/80S954djI6mxc2VVbmUVnEzvL7FbfLYojx+fmZloepTxNisLmaZtVxgpHIrkL3dJJczEcM6dOFj+8nV+eTm8tZu7V1Y5H6TjU11qpNyyIx6bmVJz5QWLS3qL2HWWARHuWx5HmuymwZRQiUDwdbBapqSj+yauXeBVgT+g+oTXqTO7f3fKM5khCY4V3tCTDJQyeLvSxu0tDYVehasYEykiCeciglTdLIzSLrE3mYvyyN3rzbLDRIg64w4GflEF/m5Sx30shLQndrAoXUHNagy5qKIhJetZWg0G10bXTalM5iC3wSuIwex61iqVfOXGgNg4Megaqa0su1PEYFgjWj/wwWx75RsljZqrOks2z1LDfPXrbbBT7y9wmUicg2WAwZRmZoJFKZ4NNlXvrI09USqMaJg+uGg80ZciKNanswKbtkbT5q6cHABHHpJ0Ek5mCQBF15AeWmTvz15Z1Jn4j3RZN21f+/2bcUlIG3F1qwP5jEnhiL10Iy8mdxf0Hz8GnqjLOAnhBRcsIgJhrsyWf5Knx3D7EIbEIPCwy6TLKMnqOEDNMO5lRlpHqbC4oCPzjY9d3dIb7OgTmYt2AZmjS70gQk0tAW2cL9Y+sgr0QaiPmFvKVq/tXSgsYe4AAVvbZnI32bNxFNph3sYh4M5ZbiF+XGnLsyEi+ZbP5iKsXWQtfb36EDaAkgN0gcbGLZZ8zdwN4Kd4OAydBrZNIWH0wa4os3L1a1eMKQ3c1fzL/3W/65UygTD+DlLPeBInYJWXgwyZp/bAAw48yfjvyjoStJQNkWQ+/0MJgXwZEwV3j6OgMU+Q/6jxO9ZkxTRwAAAABJRU5ErkJggg==";
        try {
            return ImageUtil.stringToBufferedImage(image);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static BufferedImage countImage(BufferedImage bufferedImage) {
        WinDef.RECT rect = HwndUtil.conversion(8, 4, 22, 15);
        BufferedImage count = cutImage(bufferedImage, rect);
        for (int x = rect.left; x <= rect.right; x++) {
            for (int y = rect.top; y <= rect.bottom; y++) {
                bufferedImage.setRGB(x, y, 0x00FFFFFF);
            }
        }
        return count;
    }

    public static BufferedImage cutImage(BufferedImage image, WinDef.RECT rect) {
        BufferedImage subImage = image.getSubimage(rect.left, rect.top, rect.right - rect.left + 1, rect.bottom - rect.top + 1);
        // 创建副本，以避免对原图像产生影响
        BufferedImage copy = new BufferedImage(subImage.getWidth(), subImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
        copy.getGraphics().drawImage(subImage, 0, 0, null);
        return copy;
    }

    public static WinDef.RECT getGoodsPointRect(Coordinate coordinate, int index) {
        // 每行5个，每列4个，矩形的宽度和高度
        int columns = 5;  // 每行矩形的数量
        int rows = 4;     // 每列矩形的数量
        int interval = 51;   // 矩形的宽度

        // 确保 index 在有效范围内
        if (index < 0 || index >= columns * rows) {
            return null;
        }

        // 计算行和列
        int row = index / columns; // 行
        int col = index % columns; // 列

        // 计算矩形的左上角和右下角坐标
        int left = coordinate.getX() + col * interval;
        int top = coordinate.getY() + row * interval;
        int right = coordinate.getX() + (col + 1) * interval;
        int bottom = coordinate.getY() + (row + 1) * interval;


        return HwndUtil.conversion(left, top, right, bottom);
    }

    // 提取确认截取逻辑到单独的方法
    private void performCaptureConfirmation(Logger LOGGER) throws IOException {
        inventory();
        // 获取游戏屏幕截图
        BufferedImage gameScreen = getGameScreen();
        if (gameScreen != null) {
            try {
                ImageIcon icon = new ImageIcon(gameScreen);
                // 获取 thumbnailLabel 所在面板的尺寸
                JPanel thumbnailPanel = (JPanel) thumbnailLabel.getParent();
                Dimension panelSize = thumbnailPanel.getPreferredSize();
                int panelWidth = panelSize.width;
                int panelHeight = panelSize.height;

                // 直接将图片缩放到面板的宽度和高度，忽略宽高比
                Image scaledImage = icon.getImage().getScaledInstance(
                        panelWidth,
                        panelHeight,
                        Image.SCALE_SMOOTH
                );
                ImageIcon newIcon = new ImageIcon(scaledImage);
                thumbnailLabel.setIcon(newIcon);
                thumbnailLabel.setText("");

                // 将 count 中的第一张图片放在 leftNumberLabel 里面
//                if (!count.isEmpty()) {
//                    currentIndex = 0;
//                    updateImageLabels();
//                }

                // 将 images 中的第一张图片放在 rightNumberLabel 里面
                if (!images.isEmpty()) {
                    currentIndex = 0;
                    updateImageLabels();
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                thumbnailLabel.setText("无法加载游戏截图");
            }
        } else {
            thumbnailLabel.setText("未能获取到游戏屏幕截图");
        }

    }

    // 新增辅助方法，用于在 JLabel 中显示图片
    private void showImageInLabel(ImageIcon icon, JLabel label) {
        JPanel imagePanel = (JPanel) label.getParent();
        Dimension panelSize = imagePanel.getPreferredSize();
        // 定义边距
        int widthMargin = 20;
        int heightMargin = 30;
        int panelWidth = panelSize.width - widthMargin;
        int panelHeight = panelSize.height - heightMargin;

        int imageWidth = icon.getIconWidth();
        int imageHeight = icon.getIconHeight();

        // 分别计算宽度和高度的缩放比例
        double widthRatio = (double) panelWidth / imageWidth;
        double heightRatio = (double) panelHeight / imageHeight;

        // 这里可以适当调整权重，让宽度缩放比例占主导
        double targetRatio = Math.max(widthRatio * 0.9, heightRatio);

        int scaledWidth = (int) (imageWidth * targetRatio);
        int scaledHeight = (int) (imageHeight * targetRatio);

        // 确保缩放后的宽度不超过面板宽度
        if (scaledWidth > panelWidth) {
            scaledWidth = panelWidth;
            scaledHeight = (int) (imageHeight * ((double) scaledWidth / imageWidth));
        }

        // 确保缩放后的高度不超过面板高度
        if (scaledHeight > panelHeight) {
            scaledHeight = panelHeight;
            scaledWidth = (int) (imageWidth * ((double) scaledHeight / imageHeight));
        }

        // 宽度缩小 150px
        scaledWidth -= 150;
        // 根据新的宽度重新计算高度
        scaledHeight = (int) (imageHeight * ((double) scaledWidth / imageWidth));

        // 再次确保缩放后的高度不超过面板高度
        if (scaledHeight > panelHeight) {
            scaledHeight = panelHeight;
            scaledWidth = (int) (imageWidth * ((double) scaledHeight / imageHeight));
        }

        Image scaledImage = icon.getImage().getScaledInstance(
                scaledWidth,
                scaledHeight,
                Image.SCALE_SMOOTH
        );
        ImageIcon newIcon = new ImageIcon(scaledImage);
        label.setIcon(newIcon);
        label.setText("");
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setVerticalAlignment(JLabel.CENTER);
    }

    public BufferedImage getGameScreen() {
        List<WinDef.HWND> hwnds = getHwndS("WSGAME", null);
        if (hwnds.isEmpty()) return null;
        if (robot == null) {
            try {
                robot = new Robot();
            } catch (AWTException e) {
                throw new RuntimeException(e);
            }
        }

        WinDef.RECT rect = new WinDef.RECT();
        User32.INSTANCE.GetWindowRect(hwnds.get(0), rect);
        rect.top = rect.top + 31;
        rect.left = rect.left + 8;
        rect.right = rect.right - 8;
        rect.bottom = rect.bottom - 8;
        screen = robot.createScreenCapture(rect.toRectangle());
        return screen;
    }

    public static List<WinDef.HWND> getHwndS(String className, String titleName) {
        List<WinDef.HWND> hs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            WinDef.HWND before = null;
            if (!hs.isEmpty()) before = hs.get(hs.size() - 1);
            WinDef.HWND hwnd1 = User32.INSTANCE.FindWindowEx(null, before, className, titleName);
            if (hwnd1 != null) {
                hs.add(hwnd1);
            }
        }
        return hs;
    }

    private JPanel createLeftPanel() {
        JPanel leftPanel = new JPanel(new BorderLayout());

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());

        JPanel imagePanel = new JPanel(new BorderLayout());

        thumbnailLabel = new JLabel("1");
        thumbnailLabel.setHorizontalAlignment(SwingConstants.CENTER);
        thumbnailLabel.setVerticalAlignment(SwingConstants.CENTER);
        thumbnailLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        thumbnailLabel.setPreferredSize(new Dimension(200, 200)); // 放大缩略图区域
        thumbnailLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));

        imagePanel.add(thumbnailLabel, BorderLayout.NORTH);
        topPanel.add(imagePanel, BorderLayout.NORTH);

        JPanel attributesPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.BOTH;

        // 定义展示框尺寸，高度翻倍
        int squareWidth = 350;
        int squareHeight = 300;
        squareHeight *= 2; // 高度翻倍

        // 创建两个新的面板用于分割展示图片
        JPanel leftImagePanel = new JPanel(new BorderLayout());
        leftImagePanel.setPreferredSize(new Dimension(squareWidth, squareHeight));
        leftImagePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        JPanel rightImagePanel = new JPanel(new BorderLayout());
        rightImagePanel.setPreferredSize(new Dimension(squareWidth, squareHeight));
        rightImagePanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        // 左分割面板用于显示图片
        leftNumberLabel = new JLabel();
        leftNumberLabel.setHorizontalAlignment(SwingConstants.CENTER);
        leftNumberLabel.setVerticalAlignment(SwingConstants.CENTER);
        leftImagePanel.add(leftNumberLabel, BorderLayout.CENTER);

        // 右分割面板显示图片
        rightNumberLabel = new JLabel();
        rightNumberLabel.setHorizontalAlignment(SwingConstants.CENTER);
        rightNumberLabel.setVerticalAlignment(SwingConstants.CENTER);
        rightImagePanel.add(rightNumberLabel, BorderLayout.CENTER);


        gbc.gridy = 0;
        gbc.gridx = 0;
        gbc.gridwidth = 1;
        gbc.weightx = 0.5;
        gbc.weighty = 0.5;
        attributesPanel.add(leftImagePanel, gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.5;
        attributesPanel.add(rightImagePanel, gbc);

        topPanel.add(attributesPanel, BorderLayout.CENTER);
        leftPanel.add(topPanel, BorderLayout.CENTER);

        return leftPanel;
    }

    private void updateImageLabels() {
//        if (!count.isEmpty()) {
//            BufferedImage countImage = count.get(currentIndex);
//            ImageIcon countIcon = new ImageIcon(countImage);
//            showImageInLabel(countIcon, leftNumberLabel);
//        }

        if (!images.isEmpty()) {
            image = images.get(currentIndex);
            ImageIcon imageIcon = new ImageIcon(image);
            showImageInLabel(imageIcon, rightNumberLabel);
        }

        // 更新表格渲染器的当前高亮索引
        tableCellRenderer.setCurrentHighlightIndex(currentIndex);
        table.repaint(); // 重新绘制表格以显示新的颜色
    }

    private void handlePreviousButtonClick() {
        if (currentIndex > 0) {
            currentIndex--;
            updateImageLabels();
        } else {
            JOptionPane.showMessageDialog(PropView.this, "已经是第一张图片。");
        }
    }

    private void handleNextButtonClick() {
        if (currentIndex < 19 && !images.isEmpty()) {
            currentIndex++;
            updateImageLabels();
        } else {
            JOptionPane.showMessageDialog(PropView.this, "已经是最后一张图片。");
        }
    }

    /**
     * 扫描指定文件夹中的 XML 文件并更新表格和文本区域
     * @param folder 要扫描的文件夹
     */
    private void scanXmlFiles(File folder) {
        StringBuilder xmlFiles = new StringBuilder();
        if (folder == null) {
            return;
        }
        File[] files = new File[]{folder}; // 因为现在只处理单个文件
        if (files != null) {
            // 先清空表格
            for (int row = 0; row < 4; row++) {
                for (int col = 0; col < 5; col++) {
                    int number = row * 5 + col + 1;
                    table.setValueAt(number, row, col);
                }
            }

            for (File file : files) {
                xmlFiles.append(file.getName()).append("\n");
                try {
                    // 解析 XML 文件
                    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                    Document doc = docBuilder.parse(file);

                    // 获取所有 Matrix 元素
                    NodeList matrixNodes = doc.getElementsByTagName("Matrix");
                    for (int i = 0; i < matrixNodes.getLength(); i++) {
                        Element matrixElement = (Element) matrixNodes.item(i);
                        Element positionElement = (Element) matrixElement.getElementsByTagName("Position").item(0);
                        if (positionElement != null) {
                            String positionStr = positionElement.getTextContent();
                            try {
                                int position = Integer.parseInt(positionStr);
                                // 计算表格的行和列
                                int columns = 5;
                                int row = (position - 1) / columns;
                                int col = (position - 1) % columns;
                                // 更新表格对应位置的值
                                if (row >= 0 && row < 4 && col >= 0 && col < 5) {
                                    table.setValueAt("✔", row, col);
                                }
                            } catch (NumberFormatException ex) {
                                System.err.println("位置信息不是有效的数字: " + positionStr);
                                ex.printStackTrace();
                            }
                        }
                    }
                } catch (Exception ex) {
                    System.err.println("解析 XML 文件 " + file.getName() + " 时出错: ");
                    ex.printStackTrace();
                }
            }

            xmlFilesTextArea.setText(xmlFiles.toString());
        }
    }



    private static class CustomTableCellRenderer extends DefaultTableCellRenderer {

        private int currentHighlightIndex = -1;

        public void setCurrentHighlightIndex(int index) {
            this.currentHighlightIndex = index;
        }
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            int currentIndexInTable = row * 5 + column;
            if ("✔".equals(value)) {
                c.setBackground(Color.GREEN); // 设置背景颜色为绿色
            } else if (currentIndexInTable == currentHighlightIndex) {
                c.setBackground(Color.RED); // 设置当前图片对应的单元格为红色
            }else {
                c.setBackground(table.getBackground()); // 恢复默认背景颜色
            }
            return c;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new PropView());
    }
}